extends Control

@export_group("UI")
@export var character_name_text : Label
@export var text_box : Label
@export var left_avatar : TextureRect
@export var right_avatar : TextureRect
@export_group("对话资源")
@export var main_dailogue : DialogueGroup
@onready var panel: Panel = $HBoxContainer/Panel

var dialogue_index := 0
var typing_tween : Tween


func _ready() -> void:
	display_next_dialogue()
	panel.gui_input.connect(_show_next)



func display_next_dialogue():
	if dialogue_index >= main_dailogue.dialogue_list.size():
		queue_free()
		return
	var dialogue = main_dailogue.dialogue_list[dialogue_index]
	
	if typing_tween and typing_tween.is_running():
		typing_tween.kill()
		text_box.text = dialogue.content
		dialogue_index += 1
	else:
		typing_tween = get_tree().create_tween()
		text_box.text = ""
		for charater in dialogue.content:
			typing_tween.tween_callback(append_character.bind(charater)).set_delay(0.05)
		typing_tween.tween_callback(func():
			dialogue_index += 1
			)
	
		if dialogue.show_on_left:
			left_avatar.texture = dialogue.avatar
			right_avatar.texture = null
		
		else:
			left_avatar.texture = null
			right_avatar.texture = dialogue.avatar


func append_character(character :String):
	text_box.text += character




func _show_next(event):
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.pressed == true:
			 
		display_next_dialogue()
